<template>
  <div class="resume-list">
    <div class="header">
      <h2>我的简历</h2>
      <el-button type="primary" @click="$router.push('/resumes/create')">
        <el-icon><Plus /></el-icon>
        创建新简历
      </el-button>
    </div>
    
    <div class="resume-grid">
      <el-row :gutter="20">
        <el-col :span="6" v-for="resume in resumes" :key="resume.id">
          <el-card class="resume-card" @click="editResume(resume.id)">
            <div class="resume-preview">
              <el-icon size="48" color="#409eff"><Document /></el-icon>
            </div>
            <div class="resume-info">
              <h3>{{ resume.title }}</h3>
              <p class="template-type">{{ getTemplateTypeName(resume.templateType) }}</p>
              <p class="update-time">{{ resume.updatedTime || resume.createdTime || '最近' }}</p>
              <div class="resume-actions">
                <el-button size="small" @click.stop="editResume(resume.id)">编辑</el-button>
                <el-button size="small" type="danger" @click.stop="deleteResume(resume.id)">删除</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div v-if="resumes.length === 0" class="empty-state">
      <el-icon size="100" color="#ddd"><Document /></el-icon>
      <h3>还没有简历</h3>
      <p>创建您的第一份简历吧！</p>
      <el-button type="primary" @click="$router.push('/resumes/create')">
        创建简历
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getResumeList, deleteResume as deleteResumeApi } from '@/api/resume'

const router = useRouter()

const resumes = ref([])
const loading = ref(false)

const editResume = (id) => {
  router.push(`/resumes/${id}/edit`)
}

const getTemplateTypeName = (type) => {
  const typeMap = {
    'classic': '经典模板',
    'modern': '现代简约',
    'creative': '创意设计',
    'custom': '自定义模板'
  }
  return typeMap[type] || type || '默认模板'
}

const deleteResume = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这份简历吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    try {
      // 调用后端API删除
      await deleteResumeApi(id)
      
      // 重新加载列表
      await loadResumeList()
      ElMessage.success('删除成功')
    } catch (apiError) {
      console.error('后端删除失败:', apiError)
      
      if (apiError.response?.status === 403) {
        ElMessage.error('权限不足，无法删除简历')
      } else if (apiError.response?.status === 404) {
        ElMessage.error('简历不存在')
        // 重新加载列表
        await loadResumeList()
      } else {
        ElMessage.error('删除失败，请重试')
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消，不做处理
      return
    }
    console.error('删除失败:', error)
  }
}

const loadResumeList = async () => {
  try {
    loading.value = true
    console.log('开始加载简历列表...')
    
    try {
      // 优先从后端API加载
      const response = await getResumeList()
      console.log('后端API返回数据:', response)
      
      // 解析后端返回的数据结构
      if (response.data && response.data.list) {
        resumes.value = response.data.list
      } else if (response.list) {
        resumes.value = response.list
      } else if (Array.isArray(response)) {
        resumes.value = response
      } else {
        resumes.value = []
      }
      
      console.log('解析后的简历数据，共', resumes.value.length, '份:', resumes.value)
    } catch (apiError) {
      console.error('后端API加载失败:', apiError)
      
      if (apiError.response?.status === 403) {
        ElMessage.warning('权限不足，无法访问简历列表')
      } else if (apiError.code === 'ECONNREFUSED' || apiError.message?.includes('Network Error')) {
        console.log('后端服务未启动，简历列表为空')
      }
      
      // API失败时显示空列表
      resumes.value = []
    }
  } catch (error) {
    console.error('加载简历列表失败:', error)
    resumes.value = []
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadResumeList()
})

// 组件激活时重新加载数据（用于keep-alive组件）
onActivated(() => {
  loadResumeList()
})

// 暴露loadResumeList方法，供外部调用
defineExpose({
  loadResumeList
})
</script>

<style scoped>
.resume-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.resume-grid {
  margin-bottom: 30px;
}

.resume-card {
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  margin-bottom: 20px;
}

.resume-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.resume-preview {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
}

.resume-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.resume-info p {
  color: #666;
  margin: 0 0 15px 0;
  font-size: 14px;
}

.resume-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-state h3 {
  margin: 20px 0 10px 0;
}

.empty-state p {
  margin: 0 0 30px 0;
}
</style> 